package com.rxst.msg.server.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rxst.msg.dto.search.MsgxFileSearchDto;
import com.rxst.msg.entity.MsgxFileEntity;
import com.rxst.msg.mapper.MsgxFileMapper;
import com.rxst.msg.server.MsgxFileService;
import com.rxst.msg.sso.entity.UserContext;
import com.rxst.msg.utils.UploadFileUtil;
import com.rxst.msg.vo.MsgxFileCheckVo;
import com.rxst.msg.vo.MsgxFileVo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 设备授权表
 *
 * @author rxst
 * @email rxst@gmail.com
 * @date 2021-08-19 11:47:00
 */
@Service("msgxFileService")
@Transactional(rollbackFor = Exception.class)
public class MsgxFileServiceImpl extends ServiceImpl<MsgxFileMapper, MsgxFileEntity> implements MsgxFileService {

    @Autowired
    private MsgxFileMapper mapper;

    @Autowired
    private UploadFileUtil fileUtil;

    @Value("${uploadFile.dir:}")
    private String path;

    @Value("${uploadFile.tmp:}")
    private String tmp;

    @Override
    public List<MsgxFileVo> list(MsgxFileSearchDto vo) {
        return mapper.list(vo);
    }

    @Override
    public PageInfo<MsgxFileVo> page(MsgxFileSearchDto vo) {
        PageHelper.startPage(vo.getCurrent(), vo.getSize());
        if (vo.getFileTimeType() != null && vo.getFileTimeType() == 0) {
            Date startDate = DateUtil.lastWeek();
            Date endDate = DateUtil.endOfWeek(startDate);
            vo.setStartDateTime(DateUtil.parse(DateUtil.formatDate(startDate) + " 00:00:00"));
            vo.setEndDateTime(DateUtil.parse(DateUtil.formatDate(endDate) + " 23:59:59"));
        }

        if (vo.getFileTimeType() != null && vo.getFileTimeType() == 1) {
            Date month = DateUtil.lastMonth();
            Date startMonth = DateUtil.beginOfMonth(month);
            Date endMonth = DateUtil.endOfMonth(month);
            vo.setStartDateTime(DateUtil.parse(DateUtil.formatDate(startMonth) + " 00:00:00"));
            vo.setEndDateTime(DateUtil.parse(DateUtil.formatDate(endMonth) + " 23:59:59"));
        }

        if (vo.getFileTimeType() != null && vo.getFileTimeType() == 2) {
            Date month = DateUtil.lastMonth();
            Date startMonth = DateUtil.beginOfMonth(month);
            Date day = DateUtil.offsetDay(startMonth, -1);
            vo.setEndDateTime(DateUtil.parse(DateUtil.formatDate(day) + " 23:59:59"));
        }

        PageInfo<MsgxFileVo> page = new PageInfo<>(mapper.list(vo));
        return page;
    }

    @Override
    public Boolean saveEntity(MsgxFileEntity t) {
        t.setFileId(IdUtil.fastSimpleUUID());
        return save(t);
    }

    @Override
    public Boolean saveEntityBatch(List<MsgxFileEntity> list) {
        if (CollUtil.isNotEmpty(list)) {
            for (MsgxFileEntity entity : list) {
                //todo
            }
            return saveBatch(list);
        }
        return false;
    }

    @Override
    public Boolean updateEntity(MsgxFileEntity t) {
        return updateById(t);
    }

    @Override
    public Boolean updateEntityBatch(List<MsgxFileEntity> list) {
        if (CollUtil.isNotEmpty(list)) {
            for (MsgxFileEntity entity : list) {
                //todo
            }
            return updateBatchById(list);
        }
        return false;
    }

    @Override
    public void deleteLogic(Long id) {
        mapper.deleteLogic(id);
    }

    @Override
    public void deleteLogicByIds(List<Long> ids) {
        mapper.deleteLogicByIds(ids);
    }

    @Override
    public void upload(MultipartFile file, Integer part) {
        if (part == null) {
            smallFile(file);
        } else {
            bigFile(file, part);
        }
    }

    /**
     * 大文件上传
     * 文件命名方式 第几块 + 文件大小 + 文件格式
     *
     * @param file 上传文佳
     * @param part 切割第几块
     */
    public void bigFile(MultipartFile file, Integer part) {
        String fileName = null;
        try {
            // 获取文件名
            fileName = file.getOriginalFilename();
            long size = file.getSize();
            // 获取文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String name = fileName.substring(0, fileName.lastIndexOf("."));
            // 放入到临时文件中
            File parent = new File(tmp + name);
            if (!parent.exists()) {
                parent.mkdirs();
            }
            // 执行文件到服务器
            File source = new File(parent, part + "-" + size + suffix);
            file.transferTo(source);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件错误:", e);
        }
    }

    /**
     * 小文件上传
     *
     * @param file 上传文佳
     */
    public void smallFile(MultipartFile file) {
        // 获取上传人id
        UserContext userContext = UserContext.getUserContext();
        String userId = "";
        String userName = "";
        if (userContext != null) {
            userId = UserContext.getUserContext().getCurrentUserId();
            userName = UserContext.getUserContext().getUser().getUserName();
        }
        String fileName = null;
        try {
            // 获取文件名
            fileName = file.getOriginalFilename();
            String tmpName = fileName.split("\\.")[0];
            long size = file.getSize();
            String filePath = DateUtil.format(DateUtil.date(), "yyyy" + File.separator + "MM") + File.separator + tmpName;
            File parent = new File(path + filePath);
            if (!parent.exists()) {
                parent.mkdirs();
            }
            // 执行文件到服务器
            File source = new File(parent, fileName);
            file.transferTo(source);
            //String duration = fileUtil.getDuration(source);

            String[] split = fileName.split("-");
            Date time = null;
            if (split != null && split.length > 1) {
                time = DateUtil.parse(split[1].substring(0, split[1].indexOf(".")), "yyyyMMddHHmm");
            }
            // 小文件直接存储
            MsgxFileEntity msgxFileEntity = new MsgxFileEntity();
            msgxFileEntity.setCreateBy(userId + "_" + userName);
            msgxFileEntity.setUpdateBy(userId + "_" + userName);
            msgxFileEntity.setFileId(IdUtil.fastSimpleUUID());
            msgxFileEntity.setFileName(fileName);
            msgxFileEntity.setFileUrl(filePath + File.separator + fileName);
            msgxFileEntity.setFileSize(fileUtil.formatFileSize(size));
            msgxFileEntity.setFileUserId(userId);
            //msgxFileEntity.setFileDuration(duration);
            if (time != null) {
                msgxFileEntity.setFileTranscribeTime(time);
            }
            save(msgxFileEntity);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件错误:", e);
        }
    }

    @Override
    public void mergeUpload(String name) {
        String tmpName = name.split("\\.")[0];
        String filePath = DateUtil.format(DateUtil.date(), "yyyy" + File.separator + "MM") + File.separator + tmpName;
        Map<String, Object> combine = fileUtil.combine(tmp + tmpName, path + filePath, name);
        Long fileSize = 0L;
        if (combine.get("size") != null) {
            fileSize = Long.valueOf(combine.get("size").toString());
        }
        // 获取上传人id
        UserContext userContext = UserContext.getUserContext();
        String userId = "";
        String userName = "";
        if (userContext != null) {
            userId = UserContext.getUserContext().getCurrentUserId();
            userName = UserContext.getUserContext().getUser().getUserName();
        }
        Date time = null;
        String[] split = name.split("-");
        if (split != null && split.length > 1) {
            time = DateUtil.parse(split[1].substring(0, split[1].indexOf(".")), "yyyyMMddHHmm");
        }
        // 小文件直接存储
        MsgxFileEntity msgxFileEntity = new MsgxFileEntity();
        msgxFileEntity.setCreateBy(userId + "_" + userName);
        msgxFileEntity.setUpdateBy(userId + "_" + userName);
        msgxFileEntity.setFileId(IdUtil.fastSimpleUUID());
        msgxFileEntity.setFileName(name);
        msgxFileEntity.setFileUrl(filePath + File.separator + name);
        msgxFileEntity.setFileSize(fileUtil.formatFileSize(fileSize));
        msgxFileEntity.setFileUserId(userId);
        if (time != null) {
            msgxFileEntity.setFileTranscribeTime(time);
        }
        save(msgxFileEntity);
    }

    public void mergeUpload2(String name) {
        try {
            String tmpName = name.split("\\.")[0];
            File file = new File(tmp + tmpName);
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    long fileSize = 0;
                    // 合并文件位置
                    String filePath = DateUtil.format(DateUtil.date(), "yyyy" + File.separator + "MM") + File.separator + tmpName;
                    File partFile = new File(path + filePath);
                    if (!partFile.exists()) {
                        partFile.mkdirs();
                    }
                    // 执行文件到服务器
                    File source = new File(partFile, name);
                    // 追加模式
                    for (int i = 0; i < files.length; i++) {
                        File part = files[i];
                        String partName = part.getName();
                        String[] split = partName.split("-");
                        if (split != null && split.length > 0) {
                            fileSize += Long.valueOf(split[1].substring(0, split[1].indexOf(".")));
                        }
                        FileOutputStream dest = new FileOutputStream(source, true);
                        FileUtils.copyFile(part, dest);
                        dest.close();
                    }
                    String[] split = name.split("-");
                    Date time = null;
                    if (split != null && split.length > 1) {
                        time = DateUtil.parse(split[1].substring(0, split[1].indexOf(".")), "yyyyMMddHHmm");
                    }
                    // 获取上传人id
                    UserContext userContext = UserContext.getUserContext();
                    String userId = "";
                    if (userContext != null) {
                        userId = UserContext.getUserContext().getCurrentUserId();
                    }
                    // 小文件直接存储
                    MsgxFileEntity msgxFileEntity = new MsgxFileEntity();
                    msgxFileEntity.setCreateBy(userId);
                    msgxFileEntity.setUpdateBy(userId);
                    msgxFileEntity.setFileId(IdUtil.fastSimpleUUID());
                    msgxFileEntity.setFileName(name);
                    msgxFileEntity.setFileUrl(filePath + File.separator + name);
                    msgxFileEntity.setFileSize(fileUtil.formatFileSize(fileSize));
                    msgxFileEntity.setFileUserId(userId);
                    if (time != null) {
                        msgxFileEntity.setFileTranscribeTime(time);
                    }
                    save(msgxFileEntity);
                    FileUtils.deleteDirectory(file);
                }
            }
        } catch (Exception e) {
            log.error("合并文件错误");
        }
    }

    @Override
    public MsgxFileCheckVo checkUpload(String name) {
        MsgxFileCheckVo checkVo = new MsgxFileCheckVo();
        List<Integer> part = new ArrayList<>();
        String tmpName = name.split("\\.")[0];
        File file = new File(tmp + tmpName);
        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    File temp = files[i];
                    String tempName = temp.getName();
                    String[] split = tempName.split("-");
                    if (split != null && !part.contains(split[0])) {
                        part.add(Integer.valueOf(split[0]));
                    }
                }
            }
            checkVo.setExits(false);
            checkVo.setPart(part);
        } else {
            List<MsgxFileEntity> list = lambdaQuery().eq(MsgxFileEntity::getFileName, name).list();
            if (CollUtil.isNotEmpty(list)) {
                checkVo.setExits(true);
                checkVo.setPart(part);
            } else {
                checkVo.setExits(false);
                checkVo.setPart(part);
            }
        }
        return checkVo;
    }
}

